const xlsx = require("node-xlsx");
const path = require("path");
const fs = require("fs");
const cofs = require("./cofs");

let data = xlsx.parse("a.xlsx");

let prev = [];
let rows = [];
for (let line of data[0].data) {
    for (let i = 0; i < line.length; i++) {
        prev[i] = line[i] || prev[i];
    }
    let filename = path.join.apply(null, prev.slice(0, line.length));
    rows.push(filename);
}

function check(dir) {
    return new Promise((resolve, reject) => {
        let count = rows.length;
        if (count <= 0) {
            resolve(true);
        }
        for (let i = 0; i < count; i++) {
            const filename = rows[i];
            fs.exists(path.join(dir, filename), function(ok) {
                if (ok) {
                    count--;
                    if (count <= 0) {
                        resolve(true);
                    }
                } else resolve(false);
            });
        }
    });
    for (let filename of rows) {
        if (!fs.existsSync(path.join(dir, filename))) {
            return false;
        }
    }
    return true;
}

function walk(dir) {
    return new Promise((resolve, reject) => {
        check(dir).then(ok => {
            if (ok) {
                resolve([dir]);
            } else {
                let files = fs.readdirSync(dir);
                Promise.all(files.map(x => new Promise((resolve, reject) => {
                    x = path.join(dir, x);
                    cofs.isDirectory(x).then((flag) => {
                        if (flag) {
                            walk(x).then(resolve);
                        } else {
                            resolve([]);
                        }
                    });
                }))).then(x => {
                    resolve(x.reduce((a, b) => a.concat(b), []));
                });
            }
        });
    });
}

walk(process.argv[2] || ".").then(x => console.log(x));

// fs.writeFileSync("b.xlsx", xlsx.build([{ data: rows }]));